/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myyong.test.user;

import com.mkyong.config.MongoUtil;
import com.myyong.model.User;
import java.util.List;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.data.mongodb.core.query.Query;

/**
 *
 * @author dell
 */
public class UserSearch {

    private MongoOperations mo = MongoUtil.getMongoOperations();

    public void searchUser() {
        System.out.println("#######searchUser");
        Query query = new Query(Criteria.where("firstName").is("czf1"));
        List<User> userList = mo.find(query, User.class);
        printUser(userList);
    }

    public void searchUserLimit() {
        System.out.println("#######searchUserLimit");
        Query query = new Query().limit(10);
        query.fields().include("firstName");
        query.sort().on("_id", Order.DESCENDING);
        List<User> userList = mo.find(query, User.class);
        printUser(userList);
    }

    public void searchUserExit() {
        System.out.println("#######searchUserExit");
        Query query = new Query(Criteria.where("firstName").exists(false)).limit(10);
        query.sort().on("_id", Order.DESCENDING);
        List<User> userList = mo.find(query, User.class);
        printUser(userList);
    }

    public void searchUserAddress() {
        System.out.println("#######searchUserAddress");
        Query query = new Query(Criteria.where("address.city").is("中国1"));
        query.sort().on("_id", Order.DESCENDING);
        List<User> userList = mo.find(query, User.class);
        printUser(userList);
    }

    private void printUser(List<User> userList) {
        for (User user : userList) {
            System.out.println(user);
        }
    }

    public static void main(String[] args) {
        UserSearch userSearch = new UserSearch();
        long time = System.currentTimeMillis();
        userSearch.searchUser();
        System.out.println("用了" + (System.currentTimeMillis() - time) + "毫秒");

        time = System.currentTimeMillis();
        userSearch.searchUserLimit();
        System.out.println("用了" + (System.currentTimeMillis() - time) + "毫秒");

        time = System.currentTimeMillis();
        userSearch.searchUserExit();
        System.out.println("用了" + (System.currentTimeMillis() - time) + "毫秒");
        
        time = System.currentTimeMillis();
        userSearch.searchUserAddress();
        System.out.println("用了" + (System.currentTimeMillis() - time) + "毫秒");
    }
}
